<template>
  <el-breadcrumb
    v-if="breadcrumbList && breadcrumbList.length"
    separator="/"
  >
    <el-breadcrumb-item
      v-for="(item, index) in breadcrumbList"
      :key="item.path"
    >
      <span
        v-if="item.redirect === 'noRedirect' || index == breadcrumbList.length - 1"
      >
        {{ item.meta.title }}
      </span>
      <a
        v-else
        @click.prevent="linkHandle(item)"
      >
        {{ item.meta.title }}
      </a>
    </el-breadcrumb-item>
  </el-breadcrumb>
</template>

<script lang="ts" setup name="breadcrumb">
import { ref, watch } from 'vue';

import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();

const breadcrumbList:any = ref([]);

const getBreadcrumbList = () => {
  // only show routes with meta.title
  const matched: any = route?.matched?.filter((item) => item.meta && item.meta.title) || [];

  // 如果有自定义的面包屑，使用自定义的面包屑，否则使用自动生成的
  const breadcrumbs = route?.meta?.breadcrumbs;
  if (breadcrumbs) {
    breadcrumbList.value = breadcrumbs || [];
  } else {
    breadcrumbList.value = matched.filter((item: any) => {
      if (item.meta) {
        return item.meta.title && !item.meta.hideBreadcrumb;
      }
      return false;
    });
  }
};

watch(
  route,
  (val) => {
    if (val && !val.path.startsWith('/redirect/')) {
      getBreadcrumbList();
    }
  }, {
    immediate: true,
  }
);

const linkHandle = (val: any) => {
  const { redirect, path, query } = val;
  if (redirect) {
    router.push(redirect);
    return;
  }
  router.push({
    path,
    query,
  });
};
</script>
